package com.czq.controllor;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czq.common.BaseContext;
import com.czq.common.Result;
import com.czq.dao.UserDao;
import com.czq.pojo.User;
import com.czq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserControllor {
@Autowired
private UserService userService;
@Autowired
private UserDao userDao;


@PostMapping("/loginout")

public Result logout(HttpServletRequest request){
request.getSession().removeAttribute("user");
return  Result.success("退出成功");


}


    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        String phone = user.getPhone();
        if (phone != null) {
            String code = phone.substring(7);
           request.getSession().setAttribute(phone,code);
            System.out.println(code);
            return Result.success("发送验证码成功");

        }
        else {
            return Result.error("请输入手机号");
        }
    }
    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpServletRequest request) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        String sessionCode =(String) request.getSession().getAttribute(phone);
       if (sessionCode.equals(code)){
           LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<User>();
           queryWrapper.eq(User::getPhone,phone);
           User user = userService.getOne(queryWrapper);
           QueryWrapper<User> q=new QueryWrapper<User>();
           Integer integer = userDao.selectCount(q)+1;

           if (user==null) {
               user = new User();
               user.setPhone(phone);
               user.setStatus(1);

               String  name="第"+integer+"个用户名称";
               user.setName(name);
               userService.save(user);
           }
           request.getSession().setAttribute("user",user.getId());
           return Result.success(user);
       }

       return Result.error("登录失败");
    }

}
